package mhl.service;

import mhl.dao.BillDAO;
import mhl.domain.Bill;

import java.util.List;
import java.util.UUID;

/**
 * @author DCSGO
 * @version 1.0
 */
public class BillService {
    private final BillDAO billDAO = new BillDAO();
    private final MenuService menuService = new MenuService();
    private final DiningTableService diningTableService = new DiningTableService();

    // Bill:
    //    private Integer id;
    //    private String billId;
    //    private Integer menuId;
    //    private Integer nums;
    //    private Double money;
    //    private Integer diningTableId;
    //    private Instant billDate;
    //    private String state;
    public boolean addBill(int menuId, int nums, int diningTableId) {
        String billId = UUID.randomUUID().toString();
        //菜品单价 * nums
        double money = menuService.getMenuById(menuId).getPrice() * nums;
        String sql = "insert into bill values (null,?,?,?,?,?,now(),'未结账')";
        int affectedRows = billDAO.update(sql, billId, menuId, nums, money, diningTableId);
        if (affectedRows <= 0) {//insert 失败
            return false;
        }
        return diningTableService.updateDiningTableState(diningTableId, "就餐中");
    }

    public List<Bill> getAllBill() {
        String sql = "select * from bill";
        return billDAO.queryMulti(sql, Bill.class);
    }

    public boolean hasUncheckoutBill(int dinId) {
        String sql = "SELECT * FROM bill WHERE diningTableId = ? AND state = '未结账' LIMIT 0,1;";
        return billDAO.querySingle(sql, Bill.class, dinId) != null;
    }

    public boolean updateStateByDinId(int dinId, String state) {
        String sql = "update bill set state = ? where diningTableId = ? and state = '未结账'";
        if (billDAO.update(sql, state, dinId) == 0) {
            return false;
        }
        return diningTableService.cleanDiningTable(dinId);
    }
}
